package com.suzhouhe.util.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.suzhouhe.util.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author suzhouhe @date 2020/5/20 0020 15:57 @descripte
 */
public class JsonUtil {

    private static final Logger log = LoggerFactory.getLogger(JsonUtil.class);

    private static final ObjectMapper MAPPER = new ObjectMapper();

    static {
        //忽略不存在的字段
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * 对象实体转为string
     *
     * @param obj 独享
     * @param <T> 类型
     * @return string
     */
    public static <T> String beanToStr(T obj) {
        try {
            return MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("bean to json error:", e);
            throw new ServiceException("对象转换错误");
        }
    }

    /**
     * 将数据转换为对象
     *
     * @param json 数据
     * @param type 需要转成的对象
     * @param <T>  对象类型
     * @return 对象
     */
    public static <T> T strToBean(String json, TypeReference<T> type) {
        try {
            return MAPPER.readValue(json, type);
        } catch (IOException e) {
            log.error("str toObject error:", e);
            throw new ServiceException("对象转换错误");
        }
    }

}
